package utils

import (
	"fanqiechaodan-blog/config"
	"github.com/dgrijalva/jwt-go"
	"go.uber.org/zap"
	"time"
)

var jwtKey []byte

type Claims struct {
	Uid int
	jwt.StandardClaims
}

func LoadJwtKey() {
	jwtKey = []byte(config.Cfg.System.JwtSecret)
}

func Award(uid *int) (string, error) {
	// 过期时间
	expireTime := time.Now().Add(time.Hour * 24)
	claims := &Claims{
		Uid: *uid,
		StandardClaims: jwt.StandardClaims{
			ExpiresAt: expireTime.Unix(),
			IssuedAt:  time.Now().Unix(),
		},
	}
	token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
	res, err := token.SignedString(jwtKey)
	if err != nil {
		zap.S().Errorf("生成token失败;uid:%d,原因:%s", *uid, err.Error())
		return "", err
	}
	return res, nil
}

func ParseToken(tokenStr string) (*jwt.Token, *Claims, error) {
	claims := &Claims{}
	token, err := jwt.ParseWithClaims(tokenStr, claims, func(token *jwt.Token) (interface{}, error) {
		return jwtKey, nil
	})
	if err != nil {
		zap.S().Errorf("解析token失败;原因:%s", err.Error())
		return nil, nil, err
	}
	return token, claims, nil
}
